package ru.smc.hogwarts.servlets.authorization;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.model.Person;
import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.classes.HashMd5;;

public class AuthorizationLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private String error = "";
	
    public AuthorizationLogin() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("error", error);
		error = "";
		
    	request.getRequestDispatcher("/pages/authorization/login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String password = request.getParameter("password");
    	
    	if ((login != null) && (login != "") && (password != null) && (password != "")){
    		Person user = null;
    		
       		try {
       			EntityManagerFactory emf = EMF.getInstance().getEMF();
       	    	EntityManager em = emf.createEntityManager();
       			
       			HashMd5 hash = new HashMd5();
       			try {
       				password = hash.getHash(password);
       			} catch (NoSuchAlgorithmException e) {}
	       		
	       		Query query = em.createQuery("select p from Person p where p.login = ?1 and p.password =?2");
	       		query.setParameter(1, login);
	       		query.setParameter(2, password);
	       		user = (Person)query.getSingleResult();
	       		
	       		em.close();
       		} catch (NoResultException e) {
       			error = "Неверное имя или пароль!";
       			response.sendRedirect(request.getContextPath() + "/login");
       		}
       		
       		if (user != null) {
       			HttpSession session = request.getSession(true);
       			
               	session.setMaxInactiveInterval(600);
               	session.setAttribute("userID", user.getId());
               	session.setAttribute("userFN", user.getFirstName());
               	session.setAttribute("userLN", user.getLastName());
               	session.setAttribute("userRole", user.getRole().getValue());
               	
       			response.sendRedirect(request.getContextPath() + "/");
       		}
    	}
    	else {
    		error = "Введите ваш логин и пароль!";
    		response.sendRedirect(request.getContextPath() + "/login");
    	}
    }

}

